<?php

namespace app\admin\controller\recharge;

use app\common\controller\Backend;
use app\common\model\Config;
use app\common\model\draw\Drawlog;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 充值审核
 *
 * @icon fa fa-circle-o
 */
class Recharge extends Backend
{

    /**
     * Recharge模型对象
     * @var \app\common\model\recharge\Recharge
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\recharge\Recharge;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $user_id = $this->request->request('user_id');

            $map = !empty($user_id) ? ['user_id' => $user_id] : [];

            $filter = json_decode($this->request->get("filter", ''), true);
            if (isset($filter['status']) && $filter['status'] == 3) {
                $op = $filter['status'];
                $this->request->get(['filter' => json_encode($op, true)]);
                $this->request->get(['op' => json_encode($op, true)]);
                list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            } elseif (isset($filter['status']) && $filter['status'] == 4) {
                $op = $filter['status'];
                $this->request->get(['filter' => json_encode(['status' => 0], true)]);
                $this->request->get(['op' => json_encode($op, true)]);
                list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            } elseif (isset($filter['status']) && $filter['status'] == 5) {
                $op = $filter['status'];
                $this->request->get(['filter' => json_encode(['status' => 1], true)]);
                $this->request->get(['op' => json_encode($op, true)]);
                list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            } elseif (isset($filter['status']) && $filter['status'] == 6) {
                $op = $filter['status'];
                $this->request->get(['filter' => json_encode(['status' => 2], true)]);
                $this->request->get(['op' => json_encode($op, true)]);
                list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            } else {
                list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            }
            $auth_group_access = \think\Db::name('auth_group_access')->where('uid', $this->auth->id)->find();
            if (empty($auth_group_access)) {
                $merchant = [];
            } elseif ($auth_group_access['group_id'] == 2) {
                if (isset($filter['status']) && $filter['status'] == 3) {
                    $merchant = [];
                } elseif (isset($filter['status']) && $filter['status'] > 3) {
                    $merchant = [];
                } else {
                    $merchant = ['merchant_id' => $this->auth->id];
                }
            } else {
                $merchant = [];
            }
            $list = $this->model
                ->where($where)
                ->where($merchant)
                ->where($map)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $row) {
                $row->visible(['id', 'user_id', 'username', 'phone', 'email', 'money', 'gold_money', 'type', 'image', 'status', 'create_time', 'update_time', 'examine_status', 'remark']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        $this->view->assign("admin_id", $this->auth->id);
        return $this->view->fetch();
    }


    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            //{"0":__('待审核'),"1":__('已审核'),"2":__('已驳回')}
            $examine_status = ['0' => '待审核', '1' => '已审核', '2' => '已驳回'];
            $this->view->assign('examine_status', $examine_status);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);

            if ($params['type'] == 3) {
                Db::name('user')->where('id', $params['user_id'])->setInc('money', $params['gold_money']);
                $this->handleOne([
                    'user_id' => $params['user_id'],
                    'merchant_id' => $row['merchant_id'],
                    'money' => $params['money'],
                ]);
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $params['order_sn'] = order_no();
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function handleOne(array $param)
    {
        try {

            $config = Config::where('group', 'user')->field(['id', 'name', 'value'])->select();
            $user_one_money = 0;       # 员工直属下级消费提成比例(百分比)
            $user_recharge_money = 0;  # 员工直属下级充值提成比例(百分比)
            $user_expend_money = 0;    # 员工下级直播给别人消费对方提成比例(百分比)
            foreach ($config as $value) {
                if ($value['name'] == 'user_one') {
                    $user_one_money = $value['value'];
                }
                if ($value['name'] == 'user_recharge') {
                    $user_recharge_money = $value['value'];
                }
                if ($value['name'] == 'user_expend') {
                    $user_expend_money = $value['value'];
                }
            }

            #员工直属下级充值提成比例(百分比)
            $money = 0;
            if ($param['merchant_id'] > 0) {
                $money = bcmul($param['money'], bcdiv($user_recharge_money, '100', 2), 2);
            }
            if ($money > 0) {
                $formatTime = date('Y-m-d H:i:s', time());
                Drawlog::create([
                    'merchant_id' => $param['merchant_id'],
                    'user_id' => $param['user_id'],
                    'money' => $money,
                    'type' => 1,
                    'describe' => '充值收益',
                    'create_time' => $formatTime,
                    'update_time' => $formatTime,
                ]);
            }
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }
}
